package com.gagakuai.web.encript.core;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.gagakuai.web.encript.annonation.GagakuaiDecript;
import com.gagakuai.web.encript.annonation.GagakuaiEncript;
import com.gagakuai.web.encript.config.GagakuaiEncryptProperties;
import com.gagakuai.web.encript.domain.BaseResponseApapter;
import com.gagakuai.web.encript.utils.AESUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/*
 * @program: settement
 * @description: 加密数据u
 * @author: houhong
 * @create: 2022-11-19 11:15
 */
@ControllerAdvice
@EnableConfigurationProperties(GagakuaiEncryptProperties.class)
public class EncrptResponse implements ResponseBodyAdvice<BaseResponseApapter> {

    private Logger logger = LoggerFactory.getLogger(EncrptResponse.class);

    private ObjectMapper om = new ObjectMapper();

    @Autowired
    private GagakuaiEncryptProperties properties;

    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {


        if (!returnType.hasMethodAnnotation(GagakuaiEncript.class)) {
            return false;
        }
        GagakuaiEncript gagakuaiDecript = returnType.getMethodAnnotation(GagakuaiEncript.class);
        return gagakuaiDecript.enabled();
    }


    @Override
    public BaseResponseApapter beforeBodyWrite(BaseResponseApapter body, MethodParameter returnType,
                                               MediaType selectedContentType,
                                               Class<? extends HttpMessageConverter<?>> selectedConverterType,
                                               ServerHttpRequest request, ServerHttpResponse response) {

        byte[] keyBytes = properties.getKey().getBytes();
        try {
            if (body.getMsg() != null) {
                byte[] encrypt = AESUtils.encrypt(body.getMsg(), AESUtils.generateKey());
                body.setMsg(new String(encrypt));
            }
            if (body.getObj() != null) {
                byte[] encrypt = AESUtils.encrypt(om.writeValueAsString(body.getObj()), AESUtils.generateKey());
                body.setObj(new String(encrypt));
            }
        } catch (Exception e) {
            logger.error("encript error:{}", e);
        }

        return body;

    }
}